program containermanager;

uses
  Windows,
  SysUtils,
  Dialogs,
  ShellApi,
  WSGIContainerConst in '../lib/WSGIContainerConst.pas',
  ContainerUtils in '../lib/ContainerUtils.pas',
  LMDClasses in '../lib/LMDClasses.pas';

const
  CONTAINER_EXE = 'container.exe';

var
  hWindow: HWND;
  FileParamPos: Integer;
  strWndCaption: PChar;
  AppPath: String;
  strParamFile: String;
  timer: TFrameTimer;

begin
  AppPath := ExtractFilePath(ParamStr(0));

  if FindCmdLineSwitch('caption') then
  begin
    FileParamPos := 3;
    if ParamCount < FileParamPos then
    begin
      MessageDlg('Arguments error.', mtError, [mbOK], -1);
      Exit;
    end;
    strWndCaption := PChar(ParamStr(2));
    hWindow := FindWindow(nil, strWndCaption);
  end
  else
  begin
    FileParamPos := 1;
    hWindow := FindWindow('TWSGIContainerForm', nil);
  end;

  if ParamCount = FileParamPos then
    strParamFile := ParamStr(FileParamPos)
  else
    strParamFile := '';

  if hWindow = 0 then
  begin
    if FileExists(AppPath + CONTAINER_EXE) then
      ShellExecute(0, 'open', PChar(AppPath + CONTAINER_EXE), nil,
          PChar(AppPath), SW_SHOW)
    else
      Exit;

    timer := TFrameTimer.Create;
    try
      repeat
        Sleep(100);
        hWindow := FindWindow('TWSGIContainerForm', nil);
      until (hWindow <> 0) or (timer.Time > 10.0);
    finally
      timer.Free;
    end;
    Sleep(2000);
  end;

  if strParamFile = '' then Exit;

  if not FileExists(strParamFile) then
  begin
    MessageDlg(Format('File "%s" does not exist.', [strParamFile]),
        mtError, [mbOK], -1);
    Exit;
  end;

  CopyDataToContainer(hWindow, WMCMD_OPENFILEJS,
      ExpandFileName(strParamFile));
end.
